package com.ztzh.temteam.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Objects;

public class CustomWebSocketClient  extends WebSocketClient {

    private StringBuffer buffer;

    public CustomWebSocketClient(URI serverUri, StringBuffer buffer) {
        super(serverUri);
        this.buffer = buffer;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("WebSocket connection opened.");
    }

    @Override
    public void onMessage(String message) {
        System.out.println(message);
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String content = jsonObject.getStr("content");
        if (StrUtil.isNotEmpty(content)) {
            buffer.append(content);
        }
        if (Objects.equals(jsonObject.getInt("status"), 2)) {
            System.out.println("回答内容：" + buffer);
            this.close(1000, "websocket finish");
        }
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        // Handle binary message if needed
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocket connection closed with exit code " + code + " additional info: " + reason);
    }

    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }
}
